package com.server.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.server.common.base.ProjectInfor;
import com.server.common.base.SessionData;
import com.server.service.IAttachmentService;
import com.server.service.ICommonDataService;
import com.server.service.ILoginService;
import com.server.service.ISMSCenterService;
import com.server.service.IUserManagementService;
import com.server.service.IVerifyService;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.SessionUtil;

@Controller
@RequestMapping("login")
public class LoginController {
	
	@Autowired
	private ISMSCenterService smsCenterService;
	@Autowired
	private ILoginService loginService;
	@Autowired
	private IVerifyService verifyService;
	@Autowired
	private IUserManagementService userManagementService;
	@Autowired 
	private ICommonDataService commonDataService;
	@Autowired
	private IAttachmentService attachmentService;
	
	@RequestMapping("")
	public ModelAndView loginPage(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("login");
		mv.addObject("platformName",ProjectInfor.PLATFORM_NAME);
		mv.addObject("root",ProjectInfor.ROOT_PATH);
		return mv;
	}
	
	@RequestMapping("vertify")
	public void vertify(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		Boolean isSuccess = false;
		String info = null;
		Map<String, Object> map = new HashMap<String, Object>();
		
		Map<String, Object> login = loginService.Login(name, password);
		String cardId = "";
		String userName = "";
		if(login != null && login.size() > 0 && (Boolean)login.get("isSuccess")){
			Object cardObj = login.get("CardID");
			if (cardObj != null) {
				cardId = cardObj.toString();
			}
			Object userObj = login.get("UserName");
			if (userObj != null) {
				userName = userObj.toString();
			}
			SessionUtil.setSession(request, SessionData.nameKey, userName);
			SessionUtil.setSession(request, SessionData.loginNameKey, login.get("LoginName"));
			SessionUtil.setSession(request,SessionData.cardIdKey, cardId);
			SessionUtil.setSession(request,SessionData.levelKey, login.get("Manager"));
			
			 isSuccess = true;
			 info = "登陆成功！";
			 map.put("isSuccess", isSuccess);
			 map.put("info", info);
		}else{
			 isSuccess = false;
			 info = "用户名或密码错误！";
			 map.put("isSuccess", isSuccess);
			 map.put("info", info);
		}
		OutputUtil.returnString(response, JSONSerielizer.toJson(login, null, null));
	}
	@RequestMapping("register")
	public ModelAndView RegisterPage(){
		ModelAndView mv = new ModelAndView("login/register");
		mv.addObject("platformName",ProjectInfor.PLATFORM_NAME);
		return mv;
	}
	@RequestMapping("sendCode/{telephone}")
	public void sendCode(HttpServletRequest request,HttpServletResponse response,
			@PathVariable String telephone){
		Boolean isSuccess = false;
		String info = null;
		Map<String, Object> map = new HashMap<String, Object>();
		String code = smsCenterService.registerSend(telephone);
		if(!StringUtils.isEmpty(code)){
			verifyService.addRegisterCode(telephone, code);
			isSuccess = true;
			info = "获取验证码成功";
			
		}else{
			isSuccess = false;
			info = "获取验证码失败";
			
		}
		map.put("isSuccess", isSuccess);
		map.put("info", info);
		OutputUtil.returnString( response, JSONSerielizer.toJson(map, null, null));
	}
	@RequestMapping("add")
	public void Add(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		/*String telephone = request.getParameter("telephone");
		String nickname = request.getParameter("nickname");
		String password = request.getParameter("password");
		String spassword = request.getParameter("spassword");
		String code = request.getParameter("code");
		String cCode = request.getParameter("verifyCode");
		String cverifyCode = session.getAttribute("code").toString();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = null;
		String verifyCode = null;
		
		if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(password) || StringUtils.isEmpty(nickname)) {
			isSuccess = false;
			info = "手机号、昵称、手机号不能为空!";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
		if(!cCode.equalsIgnoreCase(cverifyCode)){
			isSuccess = false;
			info = "请输入正确的验证码!";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
		if(!spassword.equals(password)){
			isSuccess = false;
			info = "两次密码不相等!";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
		if(!StringUtils.isEmpty(telephone)){
			Map<String, Object> registerCode =verifyService.getRegisterCode(telephone);
			if (registerCode != null) {
				Object codeObj = registerCode.get("code");
				if (codeObj != null) {
					verifyCode = codeObj.toString();
				}
			}
		}
		if(!verifyCode.equals(code)){
			isSuccess = false;
			info = "手机验证码输入不正确！";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}else{
			Map<String, Object> userMap = new HashMap<String, Object>();
			userMap.put("telephone", telephone);
			userMap.put("password", password);
			userMap.put("nickname", nickname);
			UUID uuid = UUID.randomUUID();
			userMap.put("uuid", uuid);
			Map<String,Object> addMap = loginservice.add(userMap);
			if((Boolean)addMap.get("isSuccess")){
				String ip = this.getIpAddr(request);
				userManagementService.login(nickname, ip, uuid.toString());
				Map<String, Object> returnMap2 = loginservice.getInfo(uuid.toString());
				if(returnMap2!=null){
					SessionUtil.setSession(request,SessionData.idKey, returnMap2.get("id"));
				}
				SessionUtil.setSession(request, SessionData.nameKey, nickname);
				SessionUtil.setSession(request, SessionData.loginUuidKey, uuid);
				SessionUtil.setSession(request, SessionData.uuidKey, uuid);
			}
			OutputUtil.returnString(response, JSONSerielizer.toJson(addMap, null, null));
		}*/
		
	}
	@RequestMapping("logout")
	public  ModelAndView logout(HttpServletRequest request){
		 //String nickName = SessionUtil.getStringAttri(request, SessionData.nameKey);
		 //String uuid = SessionUtil.getStringAttri(request, SessionData.loginUuidKey);
		 //userManagementService.logout(nickName, uuid);
		 SessionUtil.clear(request);
		 return new ModelAndView("redirect:/mng");
	}
	
	@RequestMapping("checkPhone")
	public void checkPhone(HttpServletRequest request,HttpServletResponse response){
		String telephone = request.getParameter("telephone");
		String nickname = request.getParameter("nickname");
		Map<String, Object> map = loginService.Checkphone(telephone, nickname);
		OutputUtil.returnString(response, JSONSerielizer.toJson(map, null, null));
	}
	//忘记密码页面
	@RequestMapping("forget")
	public ModelAndView forgetPassword(){
		ModelAndView mv = new ModelAndView("login/Forget_password");
		return mv;
	}
	//忘记密码修改方法
	@RequestMapping("fupdate")
	public void fupdatePassword(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		String telephone = request.getParameter("telephone");
		String password = request.getParameter("password");
		String spassword = request.getParameter("spassword");
		String code = request.getParameter("code");
		String cCode = request.getParameter("verifyCode");
		String cverifyCode = (String) session.getAttribute("code");
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = "";
		String verifyCode = "";
		if(!cCode.equalsIgnoreCase(cverifyCode)){
			isSuccess = false;
			info = "请输入正确的验证码!";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
		if(!spassword.equals(password)){
			isSuccess = false;
			info = "两次密码不相等!";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
		if(!StringUtils.isEmpty(telephone)){
			Map<String, Object> registerCode =verifyService.getRegisterCode(telephone);
			verifyCode = (String) registerCode.get("code");
			
		}
		if(!verifyCode.equals(code)){
			isSuccess = false;
			info = "手机验证码输入不正确！";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}else{
			returnMap = loginService.fupdatePassword(telephone, password);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
	}
	@RequestMapping("checkPhoneNo")
	public void checkPhoneNo(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String telephone = request.getParameter("telephone");
		Boolean isSuccess = false;
		isSuccess=loginService.checkPhoneNo(telephone);
		returnMap.put("isSuccess", isSuccess);
		OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
	}
	@RequestMapping("perfectInfo")
	public ModelAndView perfect(HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv = new ModelAndView("login/complete_info");
		/*String uuid = SessionUtil.getStringAttri(request, SessionData.uuidKey);
		Map<String, Object> userMap = loginservice.getInfo(uuid);
		mv.addObject("userName", SessionUtil.getStringAttri(request, SessionData.nameKey));
		mv.addObject("uuid", SessionUtil.getStringAttri(request, SessionData.uuidKey));
		mv.addObject("id", SessionUtil.getStringAttri(request, SessionData.idKey));
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		//mv.addObject("fileServer",PathManager.FILE_SERVER_ATTR);
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("url",  SessionUtil.getStringAttri(request, SessionData.photoUrlKey));
		mv.addObject("userMap", userMap);*/
		return mv;
	}
	@RequestMapping("save")
	public void save(HttpServletRequest request,HttpServletResponse response){
		/*String info=null;
		String operator = SessionUtil.getStringAttri(request, SessionData.nameKey);
		String uuid = SessionUtil.getStringAttri(request, SessionData.uuidKey);
		Map<String, Object> inputMap = JSONSerielizer.toMap(request.getParameter("data"));
		Boolean isSuccess = commonDataService.update(operator, "education.user", "uuid", uuid, inputMap);
		if(isSuccess){
			info = "修改成功";
		}else{
			info = "修改失败";
		}
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("isSuccess", isSuccess);
		returnMap.put("info", info);
		OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));*/
	}
	private String getIpAddr(HttpServletRequest request) { 
	       String ip = request.getHeader("x-forwarded-for"); 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
	       return ip; 
	   }
	
}
